﻿#include "socketmanager.h"
#include <QRegularExpression>
#include <QDebug>

#include <QJsonDocument>
#include <QJsonObject>

SocketManager::SocketManager()
{
    tcpSender = new QTcpSocket(this);
    tcpServer = new QTcpServer(this);
    tcpReceiver = new QTcpSocket(this);

}

bool SocketManager::initNetwork(qint16 selfPort)
{
    //绑定服务器端端口
    if(tcpServer->isListening()){
        tcpServer->close();
    }
    QVariantList listData = dbManager.queryUserInfo("UserInfo");
    QString currentIP = listData[0].toJsonObject().value("ip").toString();
    qDebug() << "currentIP:" << currentIP;
    QHostAddress addr;
    addr.setAddress(currentIP);
    tcpServer->listen(addr, selfPort);
    disconnect(tcpServer, SIGNAL(pendingConnectionAvailable()),this,SLOT(slotNewConSocket()));
    disconnect(tcpSender, SIGNAL(readyRead()),this,SLOT(slotRecMsgDataSender()));
    connect(tcpServer, SIGNAL(pendingConnectionAvailable()),this,SLOT(slotNewConSocket()));
    connect(tcpSender, SIGNAL(readyRead()),this,SLOT(slotRecMsgDataSender()));

    //发送端连接服务端(未知，权限问题会报错)
//    tcpSender->bind(QHostAddress::LocalHost, selfPort, QAbstractSocket::ShareAddress | QAbstractSocket::ReuseAddressHint);
    //主动连接后，监听回复


    int serverE = tcpServer->serverError();
    int senderE = tcpSender->error();
    if(serverE!=-1 || senderE!=-1){

        qDebug() << "初始化信息：" << tcpServer->serverError() << tcpSender->error();
        return false;
    }
    qDebug() << "初始化成功..." << tcpServer->serverError() << tcpSender->error();
    return true;

}

bool SocketManager::sendMsg(QString currentIp, qint16 currentPort, QVariantMap mapData)
{
    tcpSender->connectToHost(currentIp, currentPort, QIODeviceBase::ReadWrite, QAbstractSocket::IPv4Protocol);

    qDebug() << tcpSender->state();
    if(tcpSender->waitForConnected()){

        //发送信息
        QString name = mapData.value("name").toString();
        QString number = mapData.value("number").toString();
        QString img = mapData.value("img").toString();
        QString ip = mapData.value("ip").toString();
        QString port = mapData.value("port").toString();
        QString msg = mapData.value("msg").toString();
        QString strData;
        const char* sendData;
        strData = QString("{\"name\": \"%1\", \"number\": \"%2\", \"img\": \"%3\", \"msg\": \"%4\", \"ip\": \"%5\", \"port\": \"%6\"}").arg(name, number, img, msg, ip, port);
        QByteArray byte;
        byte = strData.toUtf8();
        sendData = byte.data();
        tcpSender->write(sendData, qstrlen(sendData));
        qDebug() << "发送的数据strData：" << strData;
        qDebug() << "发送的数据sendData：" << sendData;

        return true;
    }
    qDebug() << "服务连接失败：" << tcpSender->error();
    return false;
}

bool SocketManager::sendSelfInfoData(QString table)
{

    QVariantList listData = dbManager.queryUserInfo("UserInfo");
    QString name = listData[0].toJsonObject().value("name").toString();
    QString number = listData[0].toJsonObject().value("number").toString();
    QString img = listData[0].toJsonObject().value("img").toString();
    QString ip = listData[0].toJsonObject().value("ip").toString();
    QString port = listData[0].toJsonObject().value("port").toString();
    QString msg = "";

    if(tcpReceiver->state() == QAbstractSocket::ConnectedState){
        QString strData;
        const char* sendData;
        strData = QString("{\"name\": \"%1\", \"number\": \"%2\", \"img\": \"%3\", \"msg\": \"%4\", \"ip\": \"%5\", \"port\": \"%6\"}").arg(name, number, img, msg, ip, port);
        QByteArray byte;
        byte = strData.toUtf8();
        sendData = byte.data();
        tcpReceiver->write(sendData, qstrlen(sendData));
        qDebug() << "发送的数据strData：" << strData;
        qDebug() << "发送的数据sendData：" << sendData;
        return true;
    }
    qDebug() << "服务连接失败：" << tcpReceiver->error() << tcpReceiver->state();
    return false;
}


bool SocketManager::addOtherClient(QString currentIp, quint16 currentPort, QVariantMap mapData)
{

    static QRegularExpression re("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
    QRegularExpressionMatch match = re.match(currentIp);
    if(match.hasMatch()){
        tcpSender->connectToHost(currentIp, currentPort, QIODeviceBase::ReadWrite, QAbstractSocket::IPv4Protocol);
        qDebug() << currentIp << ":" << currentPort;
        qDebug() << tcpSender->state();
        if(tcpSender->waitForConnected()){

            //发送信息
            QString name = mapData.value("name").toString();
            QString number = mapData.value("number").toString();
            QString img = mapData.value("img").toString();
            QString ip = mapData.value("ip").toString();
            QString port = mapData.value("port").toString();
            QString msg = "";
            QString strData;
            const char* sendData;
            strData = QString("{\"name\": \"%1\", \"number\": \"%2\", \"img\": \"%3\", \"msg\": \"%4\", \"ip\": \"%5\", \"port\": \"%6\", \"isadd\": \"1\"}").arg(name, number, img, msg, ip, port);
            QByteArray byte;
            byte = strData.toUtf8();
            sendData = byte.data();
            tcpSender->write(sendData, qstrlen(sendData));
            qDebug() << "发送的数据strData：" << strData;
            qDebug() << "发送的数据sendData：" << sendData;

            return true;
        }

    }

    qDebug() << "服务连接失败：" << tcpSender->error();
    return false;
}



void SocketManager::slotRecMsgDataServer()
{
    QByteArray data;
    data = tcpReceiver->readAll();
    QString strdata = QString::fromUtf8(data);
    QJsonDocument doc = QJsonDocument::fromJson(strdata.toUtf8());
    QJsonObject obj = doc.object();
    QString name = obj.value("name").toString();
    QString number = obj.value("number").toString();
    QString img = obj.value("img").toString();
    QString msg = obj.value("msg").toString();
    QString ip = obj.value("ip").toString();
    QString port = obj.value("port").toString();
    QString isadd = obj.value("isadd").toString();
    QString self = "";

    DBManager dbManager;
    QVariantList listData = dbManager.queryDistinctPerson("TotalPerson");

    bool hasFlag = false;
    for(int i=0;i<listData.length();i++){
        QString _ip = listData[i].toJsonObject().value("ip").toString();
        QString _port = listData[i].toJsonObject().value("port").toString();
        if(ip == _ip && _port == port){
            hasFlag = true;
            break;
        }

    }
    if(!hasFlag){
        dbManager.insertDistinctPerson("TotalPerson", name, number, img, ip, port);
        sendSelfInfoData("UserInfo");
        tcpReceiver->close();
        emit flushPage();
        qDebug() << "联系人添加成功...hasFlag..." << hasFlag;
    }

    if(hasFlag){
        dbManager.insertMsgDate("TotalMsg", name, number, msg, self);
        if(isadd == "1"){
            sendSelfInfoData("UserInfo");
            qDebug() << "对方联系人添加成功...hasFlag..." << hasFlag;
        }
        else {
            emit recMsgAddRect();
        }
        tcpReceiver->close();
        qDebug() << "接收消息成功...hasFlag..." << hasFlag;
    }

    qDebug() << "json文本转化后是否为空：" << doc.isEmpty();
    qDebug() << "接收到的数据data：" << strdata;
}

void SocketManager::slotRecMsgDataSender()
{
    QByteArray data;
    data = tcpSender->readAll();
    QString strdata = QString::fromUtf8(data);
    QJsonDocument doc = QJsonDocument::fromJson(strdata.toUtf8());
    QJsonObject obj = doc.object();
    QString name = obj.value("name").toString();
    QString number = obj.value("number").toString();
    QString img = obj.value("img").toString();
//    QString msg = obj.value("msg").toString();
    QString ip = obj.value("ip").toString();
    QString port = obj.value("port").toString();


    QVariantList listData = dbManager.queryDistinctPerson("TotalPerson");

    bool hasFlag = false;
    for(int i=0;i<listData.length();i++){
        QString _ip = listData[i].toJsonObject().value("ip").toString();
        QString _port = listData[i].toJsonObject().value("port").toString();
        if(ip == _ip && _port == port){
            hasFlag = true;
            break;
        }

    }
    if(!hasFlag){
        dbManager.insertDistinctPerson("TotalPerson", name, number, img, ip, port);
        emit flushPage();
        qDebug() << "联系人添加成功...hasFlag..." << hasFlag;
    }

    qDebug() << "json文本转化后是否为空：" << doc.isEmpty();
    qDebug() << "接收到的数据data：" << strdata;
}

void SocketManager::slotNewConSocket()
{
    //断开旧连接
    tcpReceiver->close();
    disconnect(tcpReceiver, SIGNAL(readyRead()),this,SLOT(slotRecMsgDataServer()));

    tcpReceiver = tcpServer->nextPendingConnection();
    qDebug() << "新的连接被创建...连接状态：" << tcpReceiver->state();

    connect(tcpReceiver, SIGNAL(readyRead()),this,SLOT(slotRecMsgDataServer()));
}

